package com.edu.controller;

import com.edu.Result;
import com.edu.StatusCode;
import com.edu.pojo.EduStu;
import com.edu.service.EduStuService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 学生管理控制层
 *
 * @author YJF
 */
@RestController
@RequestMapping("/stu")
public class EduStuController {

    @Autowired
    private EduStuService eduStuService;

    /**
     * 查找所有学生信息
     */
    @GetMapping("/all")
    public Result findAll() {
        List<EduStu> stuList = eduStuService.findAll();
        return new Result(true, StatusCode.OK, "查找成功!", stuList);
    }

    /**
     * 分页条件查询学生的信息
     */
    @GetMapping("/list")
    public Result findByPage(HttpServletRequest request) {
        String page = request.getParameter("page");
        String size = request.getParameter("size");
        String stuId = request.getParameter("queryNo");
        String stuName = request.getParameter("queryName");
        EduStu eduStu = new EduStu();
        if (!"".equals(stuId) && stuId.length() > 0) {
            eduStu.setStuId(Long.valueOf(stuId));
        }
        eduStu.setStuName(stuName);
        PageInfo<EduStu> stuList = eduStuService.findStu(page, size, eduStu);
        return new Result(true, StatusCode.OK, "查询成功!", stuList);
    }

    /**
     * 添加学生
     */
    @PostMapping("/add")
    public Result addStu(@RequestBody EduStu eduStu) {
        int status = eduStuService.addStu(eduStu);
        if (status == StatusCode.OK) {
            return new Result(true, StatusCode.OK, "添加成功!", eduStu);
        } else if (status == StatusCode.REP_ERROR) {
            return new Result(false, StatusCode.REP_ERROR, "添加失败,已存在!");
        }
        return new Result(false, StatusCode.ERROR, "添加失败,未知错误!");
    }

    /**
     * 根据学号查询学生信息
     */
    @GetMapping("/one/{stuId}")
    public Result findOneById(@PathVariable("stuId") Long stuId) {
        EduStu eduStu = eduStuService.findOneById(stuId);
        return new Result(true, StatusCode.OK, "查询成功!", eduStu);
    }

    /**
     * 修改学生信息
     */
    @PutMapping("/update")
    public Result updateStu(@RequestBody EduStu eduStu) {
        int status = eduStuService.updateStu(eduStu);
        System.out.println("修改了" + status + "条选课信息");
        return new Result(true, StatusCode.OK, "更新成功!", eduStu);
    }

    /**
     * 根据学号删除学生信息
     */
    @DeleteMapping("/del/{id}")
    public Result delById(@PathVariable("id") Long id) {
        int status = eduStuService.delById(id);
        if (status > 0) {
            return new Result(true, StatusCode.OK, "删除成功!", id);
        }
        return new Result(false, StatusCode.ERROR, "删除失败!", id);
    }

}
